package com.example.p2pinvest.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.example.p2pinvest.R;
import com.example.p2pinvest.activity.GestureEditActivity;
import com.example.p2pinvest.activity.GuiGuInvestActivity;
import com.example.p2pinvest.activity.UserRegisterActivity;
import com.example.p2pinvest.common.AppNetConfig;
import com.example.p2pinvest.common.BaseActivity;
import com.example.p2pinvest.common.BaseFragment;
import com.example.p2pinvest.util.UIUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mob.MobSDK;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cz.msebera.android.httpclient.Header;

/**
 * @author h2tc01
 * @version 1.0.0
 * 2022/8/2
 */
public class MoreFragment extends BaseFragment {

    @BindView(R.id.iv_title_back)
    ImageView ivTitleBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_title_setting)
    ImageView ivTitleSetting;
    @BindView(R.id.tv_more_register)
    TextView tvMoreRegister;
    @BindView(R.id.toggle_more)
    ToggleButton toggleMore;
    @BindView(R.id.tv_more_reset)
    TextView tvMoreReset;
    @BindView(R.id.rl_more_contact)
    RelativeLayout rlMoreContact;
    @BindView(R.id.tv_more_feedback)
    TextView tvMoreFeedback;
    @BindView(R.id.tv_more_share)
    TextView tvMoreShare;
    @BindView(R.id.tv_more_about)
    TextView tvMoreAbout;
    @BindView(R.id.tv_more_phone)
    TextView tvMorePhone;

    private SharedPreferences sp;

    @Override
    protected RequestParams getParams() {
        return null;
    }

    @Override
    protected String getUrl() {
        return null;
    }

    @Override
    public void initData(String content) {

        //初始化sp
        sp = this.getActivity().getSharedPreferences("secret_protect", Context.MODE_PRIVATE);

        //获取当前手势密码是否开启
        getGestureStatus();

        //设置手势密码
        setGesturePassword();

        //重置手势密码
        resetGesturePassword();

        //联系客服
        contactService();

        //用户反馈
        userFeedback();

        //分享给好友
        shareToFriends();

        //关于硅谷理财
        aboutInvest();
    }

    private void aboutInvest() {
        tvMoreAbout.setOnClickListener(v -> {
            ((BaseActivity) MoreFragment.this.getActivity()).gotoActivity(GuiGuInvestActivity.class, null);
        });
    }

    private void shareToFriends() {
        tvMoreShare.setOnClickListener(v -> {
            MobSDK.submitPolicyGrantResult(true);
            Platform.ShareParams sp = new Platform.ShareParams();
            sp.setTitle("测试分享的标题");
            // 标题的超链接
            sp.setTitleUrl("http://sharesdk.cn");
            sp.setText("测试分享的文本");
            sp.setImageUrl("https://assets.perfectdomain.com/_domainphoto/4/3/a/c/43ac0d2ba062bc36f7ba1056b5f63fbd_o.jpg");
            Platform qq = ShareSDK.getPlatform(QQ.NAME);
            // 设置分享事件回调（注：回调放在不能保证在主线程调用，不可以在里面直接处理UI操作）
            qq.setPlatformActionListener(new PlatformActionListener() {
                public void onError(Platform arg0, int arg1, Throwable arg2) {
                    // 失败的回调，arg:平台对象，arg1:表示当前的动作(9表示分享)，arg2:异常信息
                    Log.e("TAG", "onError: " + arg1 + arg2.getMessage());
                }

                public void onComplete(Platform arg0, int arg1, HashMap arg2) {
                    // 分享成功的回调
                    Log.e("TAG", "onComplete: " + arg1 + arg2.toString());
                }

                public void onCancel(Platform arg0, int arg1) {
                    // 取消分享的回调
                    Log.e("TAG", "onCancel: " + arg1);
                }
            });
            // 执行分享
            qq.share(sp);
        });
    }

    private void userFeedback() {
        tvMoreFeedback.setOnClickListener(v -> {
            View view = View.inflate(MoreFragment.this.getActivity(), R.layout.view_feedback, null);
            new AlertDialog.Builder(MoreFragment.this.getActivity())
                    .setView(view)
                    .setPositiveButton("确定", (dialog, which) -> {

                        RadioGroup rgFeedback = view.findViewById(R.id.rg_fankui);
                        RadioButton radioButton = rgFeedback.findViewById(rgFeedback.getCheckedRadioButtonId());
                        String department = radioButton.getText().toString();

                        EditText etFeedbackContent = view.findViewById(R.id.et_fankui_content);
                        String content = etFeedbackContent.getText().toString().trim();

                        //发送反馈信息给服务器
                        RequestParams params = new RequestParams();
                        params.add("department", department);
                        params.add("content", content);
                        client.post(AppNetConfig.FEEDBACK, params, new AsyncHttpResponseHandler() {
                            @Override
                            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                                UIUtils.toast("发送反馈信息成功", false);
                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                                UIUtils.toast("上传反馈信息失败", false);
                            }
                        });
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });
    }

    private void contactService() {
        rlMoreContact.setOnClickListener(v -> {
            new AlertDialog.Builder(MoreFragment.this.getActivity())
                    .setTitle("联系客服")
                    .setMessage("是否现在联系客服")
                    .setPositiveButton("确定", (dialog, which) -> {
                        //获取手机号码
                        String phone = tvMorePhone.getText().toString().trim();
                        //隐式视图,启动系统拨号界面
                        Intent intent = new Intent(Intent.ACTION_CALL);
                        intent.setData(Uri.parse("tel:" + phone));
                        MoreFragment.this.getActivity().startActivity(intent);
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });
    }

    private void resetGesturePassword() {
        tvMoreReset.setOnClickListener(v -> {
            boolean checked = toggleMore.isChecked();
            if (checked) {
                ((BaseActivity) this.getActivity()).gotoActivity(GestureEditActivity.class, null);
            } else {
                UIUtils.toast("手势密码操作已关闭,请开启后再设置", false);
            }
        });
    }

    /**
     * 获取手势密码是否开启
     */
    private void getGestureStatus() {
        boolean isOpen = sp.getBoolean("isOpen", false);
        toggleMore.setChecked(isOpen);
    }

    private void setGesturePassword() {
        toggleMore.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                String inputCode = sp.getString("inputCode", "");
                if (TextUtils.isEmpty(inputCode)) {
                    //没有手势密码,询问是否设置手势密码
                    new AlertDialog.Builder(MoreFragment.this.getActivity())
                            .setTitle("设置手势密码")
                            .setMessage("是否现在设置手势密码")
                            .setPositiveButton("确定", (dialog, which) -> {
                                sp.edit().putBoolean("isOpen", true).apply();
                                ((BaseActivity) MoreFragment.this.getActivity()).gotoActivity(GestureEditActivity.class, null);
                            })
                            .setNegativeButton("取消", (dialog, which) -> {
                                UIUtils.toast("取消现在设置手势密码", false);
                                sp.edit().putBoolean("isOpen", false).apply();
                                toggleMore.setChecked(false);
                            })
                            .show();
                } else {
                    //有手势密码
                    UIUtils.toast("开启了手势密码", false);
                    sp.edit().putBoolean("isOpen", true).apply();
                }
            } else {
                //UIUtils.toast("关闭了手势密码", false);
                //sp.edit().putBoolean("isOpen", false).apply();
            }
        });
    }

    @OnClick(R.id.tv_more_register)
    public void userRegister(View view) {
        ((BaseActivity) this.getActivity()).gotoActivity(UserRegisterActivity.class, null);
    }

    @Override
    public void initTitle() {
        ivTitleBack.setVisibility(View.GONE);
        tvTitle.setText("更多");
        ivTitleSetting.setVisibility(View.GONE);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_more;
    }
}
